import { observer } from "mobx-react-lite";
import observableTodoStore, { TodoItemType, ObservableTodoStore } from './store/TodoStore';

const TodoList = observer<{ store: ObservableTodoStore }>(({store}) => {
  const onNewTodo = () => {
    const _task = prompt('Enter a new todo:','coffee plz');
    _task && store.addTodo(_task);
  }

  return (
    <div>
      { store.report }
      <ul>
        { store.todos.map(
          (todo, idx) => <TodoView todo={ todo } key={ idx } />
        ) }
      </ul>
      { store.pendingRequests > 0 ? <div>Loading...</div> : null }
      <button onClick={ onNewTodo }>New Todo</button>
      <small> (double-click a todo to edit)</small>
      {/* <RenderCounter /> */}
    </div>
  );
})

const TodoView = observer<{ todo: TodoItemType }>(({todo}) => {
  const onToggleCompleted = () => {
    todo.completed = !todo.completed;
  }

  const onRename = () => {
    todo.task = prompt('Task name', todo.task) || todo.task;
  }

  return (
    <li onDoubleClick={ onRename }>
      <input
        type='checkbox'
        checked={ todo.completed }
        onChange={ onToggleCompleted }
      />
      { todo.task }
      { todo.assignee
        ? <small>{ todo.assignee.name }</small>
        : null
      }
      {/* <RenderCounter /> */}
    </li>
  );
});

const App = () => <TodoList store={ observableTodoStore } />;

// MARK: 我们可以直接改变 store 的内容去触发 react 视图的更新
// @ts-ignore
// window.store = observableTodoStore;
// store.todos[0].completed = !store.todos[0].completed;
// store.todos[1].task = "Random todo " + Math.random();
// store.todos.push({ task: "Find a fine cheese", completed: true });

export default App;